<?php
class Mincoding_VendorConnect_Model_Observer
{
    const VENDOR_ATTR_CODE = 'vendors';
    
    public function getConnectionRead()
    {
        return $connection = Mage::getSingleton('core/resource')->getConnection('core_read');    
    }
    
    public function getConnectionWrite()
    {
        return $connection = Mage::getSingleton('core/resource')->getConnection('core_write');    
    }
    
    public function checkAttributeValueExists($arg_attribute, $arg_value)
    {
    	$attribute_model        = Mage::getModel('eav/entity_attribute');
    	$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
    
    	$attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
    	$attribute              = $attribute_model->load($attribute_code);
    
    	$attribute_table        = $attribute_options_model->setAttribute($attribute);
    	$options                = $attribute_options_model->getAllOptions(false);
    	foreach($options as $option)
    	{
    		if ($option['label'] == $arg_value)
    		{
    		  return $option['value'];
    		}
    	}
    	return false;
    }
    
    public function removeVendor($observer)
    {
        $vendorName = $observer->getName();
        $removeVendor = $observer->getRemoveVendor();
        if ( $removeVendor == 'yes' )
        {
            $option_id = $this->checkAttributeValueExists(self::VENDOR_ATTR_CODE, $vendorName);
            if ( $option_id !== false )
            { 
                $this->removeAttributeOptionValue($option_id);    
            }            
        }
    }
    public function removeAttributeOptionValue($option_id)
    {
        $attribute = Mage::getModel('eav/config')->getAttribute('catalog_product',self::VENDOR_ATTR_CODE);
        $collection = Mage::getResourceModel('eav/entity_attribute_option_collection')
            ->setAttributeFilter($attribute->getId())
            ->setStoreFilter($attribute->getStoreId())
            ->addFieldToFilter('main_table.option_id', array('in' => $option_id))
            ->load();
        foreach ($collection as $option) {
            $option->delete();
        }     
    }
 
    public function updateVendorOption($observer)
    {
        $formFilter = new Varien_Data_Form_Filter_Escapehtml();
        $vendor = $observer->getVendor();
        $origin_model = $observer->getData('origin_model');
        $request = $observer->getRequest();
        
        $vendorName = $vendor->getName();
        $rename_vendor_name = $request->getParam('rename_vendor_name',0);
        
        //stop process for in_active, no updating, no adding
        if ( !$request->getParam('is_active',0) ) {
            $option_id = $this->checkAttributeValueExists(self::VENDOR_ATTR_CODE, $vendorName);
            if ( $option_id !== false )
            { 
                $this->removeAttributeOptionValue($option_id);    
            } 
            return;
        }
        
        $attribute_model        = Mage::getModel('eav/entity_attribute');
        $attribute_id         = $attribute_model->getIdByCode('catalog_product', self::VENDOR_ATTR_CODE);
        $attribute              = $attribute_model->load($attribute_id);

        //$coreWrite = $this->getConnectionWrite();//Magento_Db_Adapter_Pdo_Mysql
        
        if(!$this->checkAttributeValueExists(self::VENDOR_ATTR_CODE, $vendorName) && $rename_vendor_name != 1 )
        {
        	$value['option'] = array($vendorName);
        	$order['option'] = array();
        	$result =  array(
                'value' => $value,'order' => $order
            );
        	$attribute->setData('option',$result);
        	$attribute->save();
        }
        else if ( $rename_vendor_name == 1 )
        {
            //rename vendor name -- update vendor name from existings
            $oldVendorName = $origin_model->getName();
            $option_id = $this->checkAttributeValueExists(self::VENDOR_ATTR_CODE, $oldVendorName);
            
            $coreWrite = $this->getConnectionWrite();//var_dump($option_id);die;
            //echo get_class($coreWrite);die;
            if ( $option_id !== false )
            {
                //$attribute_value_model = Mage::getModel('eav/entity_attribute_option');   
                $query = "SELECT value_id FROM " . $coreWrite->getTableName('eav_attribute_option_value') . " WHERE store_id=0 AND option_id=$option_id";
                //echo $query, "<hr/>";die;
                $row = $coreWrite->fetchRow($query);//var_dump($row);die;
                if ( $row && $row['value_id'] )
                {
                    
                    $query = "UPDATE `" . $coreWrite->getTableName('eav_attribute_option_value') . "` SET value=:value WHERE value_id=:value_id;";
                    $binds = array(
                        'value' => $vendorName, //$formFilter->outputFilter($vendorName),
                        'value_id' => $row['value_id']
                    );
                    $coreWrite->query($query,$binds);
                }
            }
            //var_dump($option_id,$oldVendorName);
            
        }
    }    
    //get selected default from contracts
    public function editProduct($observer)
    {
        $product = $observer->getProduct();
        //sychronize data to product
        $this->updateContractIdsForProduct($product);  
    }
    
    public function updateContractIdsForProduct($product)
    {
        $connectionRead = Mage::helper('vendorconnect')->getReaderConnection();
        $product_id = $product->getId();
        $table = $connectionRead->getTableName('mincoding_contract_product_flat');
        $query = "SELECT GROUP_CONCAT(contract_id) AS contract_ids FROM $table WHERE  FIND_IN_SET($product_id,product_ids)";
        $contracts = $connectionRead->fetchRow($query);   
        if ( $contracts && isset($contracts['contract_ids']) && $contracts['contract_ids'] )
        {
            
            $product->setData('contract_ids',$contracts['contract_ids']);
            $product->getResource()->saveAttribute($product, 'contract_ids');  
            //$product->save();
            //return $contracts['contract_ids'];
        }
        else 
        {
            $product->setData('contract_ids','');
            $product->getResource()->saveAttribute($product, 'contract_ids');      
        }
    }
    
    
    public function updateContractIdsToProduct($observer)
    {
        $product = $observer->getProduct();
        $this->updateContractIdsForProduct($product);  
    }
    
    public function updateContractProduct($observer)
    {
        $product = $observer->getProduct();
        $product_id = $product->getId();
        $contract_ids = $product->getData('contract_ids');
        $id = Mage::app()->getRequest()->getParam('id',null);
        
        if ( $product_id == $id && $id )
        {
            //$connectionRead = Mage::helper('vendorconnect')->getReaderConnection();
            $writeConnection = Mage::helper('vendorconnect')->getWriteConnection();
            if ( !$contract_ids )
            {
                //remove all product in contract
                $contractProductResource = Mage::getResourceModel('vendorconnect/contractproduct');
                $contractProductResource->removeProducts($product_id,1);
                
                //remove from mincoding_contract_product_flat table
                $table = $writeConnection->getTableName('mincoding_contract_product_flat');
                $query = "SELECT contract_id,product_ids FROM $table WHERE FIND_IN_SET($product_id,product_ids)";
                $contracts = $writeConnection->fetchAll($query);   
                if ( $contracts && is_array($contracts) )
                {
                    foreach ( $contracts as $contract_row )
                    {
                        $product_ids = explode(',',$contract_row['product_ids']); 
                        if ( $product_ids && is_array($product_ids) && ($key = array_search($product_id, $product_ids)) !== false )           
                        {
                            unset($product_ids[$key]);    
                        }    
                        if ( $product_ids && is_array($product_ids) )
                        {
                            $query = "UPDATE `$table` SET product_ids='" . implode(',',$product_ids) . 
                                "' WHERE contract_id='".$contract_row['contract_id']."'";    
                            $writeConnection->query($query);
                        }     
                    }
                }
                return;
            }
            //this case user update contracts to product
            
            $contractIds = explode(',',$contract_ids);
            //echo "<pre>"; var_dump($contract_ids);die;
            
            //not in contract => remove product
            $table = $writeConnection->getTableName('mincoding_contract_product_flat');
            $query = "SELECT contract_id,product_ids FROM $table WHERE FIND_IN_SET($product_id,product_ids) AND 
            ( NOT FIND_IN_SET(contract_id,'$contract_ids') )";
            $contracts = $writeConnection->fetchAll($query); 
          
            if ( $contracts &&  is_array($contracts) )
            {
                foreach ( $contracts as $contract_row )
                {
                    $product_ids = explode(',',$contract_row['product_ids']);
                    
                    if ( $product_ids && is_array($product_ids) && ($key = array_search($product_id, $product_ids)) !== false )           
                    {
                        unset($product_ids[$key]);  
                    }
                    if ( $product_ids && is_array($product_ids) )
                    {
                        $query = "UPDATE `$table` SET product_ids='" . implode(',',$product_ids) . 
                            "' WHERE contract_id='".$contract_row['contract_id']."'";    
                        $writeConnection->query($query);
                    }     
                    $contractProductResource = Mage::getResourceModel('vendorconnect/contractproduct');
                    $contractProductResource->removeProducts($product_id . "," . $contract_row['contract_id'],2);
                }
            }
            
            foreach ( $contractIds as $contract_id )
            {
                //check if exist not add to contractproduct
                $contractProductResource = Mage::getResourceModel('vendorconnect/contractproduct');
                $condition = "product_id='$product_id' AND contract_id='$contract_id'";
                //var_dump($contractProductResource->checkContractProductExist($condition));
                if ( $contractProductResource->checkContractProductExist($condition) === false )
                {
                    //add product with new contract
                    $dateItem = array(
                        'contract_id' => $contract_id,
                        'product_id' => $product_id,
                        'created_time' => date("Y-m-d H:i:s"),
                    );
                    $contractProductResource->addNewContractProduct($dateItem);
                }
                
                //check if exist not update mincoding_contract_product_flat
                $dateItem = array(
                    'contract_id' => $contract_id,
                    'product_id' => $product_id,
                );
                $contractProductResource->addNewContractProductFlatProductAfterSave($dateItem);
                /*$condition = "FIND_IN_SET($product_id,product_ids) AND contract_id='$contract_id'";
                $row = $contractProductResource->checkContractProductFlatExist($condition);
                if ( $row && isset($row['contract_id']) && $row['contract_id'] )
                {
                    //existed, so must update
                    
                }
                else 
                {
                    //add new
                    
                }*/
            } //die("gogog");
            //echo "<pre>"; var_dump($contractIds);die;
        }
    }
}